package com.yfjin.fbus;

import com.yfjin.fbus.request.RequestBean;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

public class NameCenter {


    private static final NameCenter mInstance = new NameCenter();


    public static NameCenter getInstance() {
        return mInstance;
    }


    private final ConcurrentHashMap<String, Class<?>> mClassMap = new ConcurrentHashMap<>();


    private final ConcurrentHashMap<String, ConcurrentHashMap<String, Method>> mAllMethodMap = new ConcurrentHashMap<>();

    private final ConcurrentHashMap<String, Object> mInstanceObjectMap = new ConcurrentHashMap<>();


    public void register(Class<?> clazz) {
        mClassMap.put(clazz.getName(), clazz);


        Method[] methods = clazz.getMethods();
        for (Method m : methods) {
            ConcurrentHashMap<String, Method> methodMaps = mAllMethodMap.get(clazz.getName());
            if (methodMaps == null) {
                methodMaps = new ConcurrentHashMap<>();
                mAllMethodMap.put(clazz.getName(), methodMaps);
            }
            String key = getMethodParamters(m);
            methodMaps.put(key, m);
        }
    }

    private static String getMethodParamters(Method m) {
        StringBuilder sb = new StringBuilder();
        sb.append(m.getName());
        Class<?>[] classes = m.getParameterTypes();
        int len = classes.length;
        if (len == 0) {
            return sb.toString();
        }
        for (Class<?> aClass : classes) {
            sb.append("-").append(aClass.getName());
        }
        return sb.toString();
    }

    public Method getMethod(RequestBean request) {

        ConcurrentHashMap<String, Method> m = mAllMethodMap.get(request.getClassName());
        if (m != null) {
            String key = getMethodParamters(request);
            return m.get(key);
        }

        return null;
    }

    private String getMethodParamters(RequestBean request) {
        StringBuilder sb = new StringBuilder();
        sb.append(request.getMethodName());

        if (request.getRequestParamters() == null || request.getRequestParamters().length > 0) {
            return request.toString();
        }

        RequestBean.RequestParamter[] requestParamters= request.getRequestParamters();
        
        int len = requestParamters.length;
        for (int i = 0; i < len; i++) {
            sb.append("-").append(requestParamters[i].getParameterClassName());
        }

        return sb.toString();
    }

    public Class<?> getClassType(String clazzName) {
        try {
            Class<?> clazz=Class.forName(clazzName);
            return clazz;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
